package com.xh.petdogexpert.user.service.imp;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.base.ValudateForm;
import com.xh.petdogexpert.base.ValudateForm.FormField;
import com.xh.petdogexpert.base.tool.FileRead;
import com.xh.petdogexpert.expert.dto.Dog;
import com.xh.petdogexpert.expert.service.IDogService;
import com.xh.petdogexpert.sys.service.ILoginService;
import com.xh.petdogexpert.user.dto.User;
import com.xh.petdogexpert.user.dto.UserDogLink;
import com.xh.petdogexpert.user.mapper.UserDogLinkMapper;
import com.xh.petdogexpert.user.mapper.UserMapper;
import com.xh.petdogexpert.user.service.IUserService;

import xin.email.SendMail;

@Transactional
@Service
public class UserServiceImp implements IUserService {

	@Autowired
	UserMapper userMapper;

	@Autowired
	ValudateForm valudateForm;

	@Autowired
	HttpSession session;

	@Autowired
	SendMail sendEmailService;

	@Autowired
	ILoginService loginService;

	private Logger logger = LoggerFactory.getLogger(UserServiceImp.class);

	public boolean forgetPassword(String email) throws Exception {

		String forgetMsg = FileRead.read("/email_message/forgetPassword.html");
		System.out.println(forgetMsg);
		;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
		forgetMsg = forgetMsg.replaceAll("\\$\\{email\\}", email)
				.replaceAll("\\$\\{url\\}", sendEmailService.getEncodeUrl(email))
				.replaceAll("\\$\\{time\\}", format.format(new Date()));
		System.out.println(sendEmailService.getEncodeUrl(email));
		;
		sendEmailService.sendEmail(email, "宠物犬疾病诊断系统忘记密码", forgetMsg);

		return true;
	}

	@Override
	public List<User> queryUsers(User user) {

		List<User> users = userMapper.queryUsers(user);

		return users;
	}

	@Override
	public int addUpdateUser(User user) throws BaseException {
		// 校验程序
		validateUser(user);
		user.setLoginTime(new Date());
		user.setStatus(1);

		try {
			if (user.getId() != null)
				return userMapper.updateByPrimaryKeySelective(user);
			else
				return userMapper.addUser(user);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("增加用户出错");
		}

	}

	@Override
	public User getUser(User user) throws BaseException {
		List<User> users = userMapper.queryUsers(user);
		if (users.size() > 1) {
			throw new BaseException("获取多于一个用户的数据");
		} else if (users == null || users.size() == 0) {
			throw new BaseException("不存在此用户的数据");
		} else {
			return users.get(0);
		}

	}

	@Override
	public int deleteUser(User user) throws BaseException {
		int count;
		try {
			count = userMapper.deleteUser(user);

		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("删除失败");
		}

		return count;
	}

	@Override
	public User getMyInfo() {
		User user = (User) session.getAttribute("user");
		System.out.println(user);
		return user;
	}

	@Override
	public String resetPasswordShow(String key) {
		String email = sendEmailService.valudate(key);
		return email;
	}

	@Override
	public String resetPassword(String password, String key) throws BaseException {
		try {
			String email = sendEmailService.valudate(key);
			User user = new User();
			user.setEmail(email);
			user.setPassword(password);
			System.out.println(email);
			if (email != null) {
				int st = userMapper.updatePasswordByEmail(user);
				if (st == 0) {
					throw new BaseException("修改失败");
				}
			}
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("修改失败");
		}
	}

	@Override
	public String resetPassword(String nickname, String email, String password) throws BaseException {
		
		if(nickname == null || password == null || email == null) {
			throw new BaseException("修改出错");
		}
		
		try { 
			User user = new User();
			user.setEmail(email);
			user.setPassword(password);
			user.setNickname(nickname);
			
			System.out.println(email);
			;
			if (email != null) {
				int st = userMapper.updatePasswordByEmail(user);
				if (st == 0) {
					throw new BaseException("修改失败");
				}
			}
			return "修改成功";
		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("修改失败");
		}
	}
	
	@Autowired
	UserDogLinkMapper userDogLinkMapper;

	public List<UserDogLink> getMyDogs() {

		User user = (User) session.getAttribute("user");
		int id = user.getId();
		List<UserDogLink> userDogs = getDogsByUserId(id);
		return userDogs;

	}

	@Autowired
	IDogService dogService;

	public List<UserDogLink> getDogsByUserId(Integer id) {
		List<UserDogLink> userDogs = userDogLinkMapper.getUserDogs(id);

		Dog dog = new Dog();
		for (UserDogLink userDogLink : userDogs) {
			dog.setId(userDogLink.getDogId());
			List<Dog> dogs = dogService.queryDogs(dog);
			userDogLink.setDog(dogs.get(0));
		}

		return userDogs;
	}

	public void validateUser(User user) throws BaseException {
		// 校验程序
		valudateForm.init();

		valudateForm.valudate(new FormField("password", user.getPassword()), (data) -> {
			String password = (String) data;

			if (password != null && password.length() < 8)
				return "密码位数小于8位";

			return null;
		});

		valudateForm.throwError();

	}
	
	
	// 注册
	@Override
	public int register(User user) throws BaseException {

		validateUser(user);

		user.setLoginTime(new Date());
		user.setRoleId(3);
		user.setStatus(1);

		try {
			int userId = userMapper.addUser(user);
			loginService.login(user);
			return userId;

		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("注册出错");
		}
	}

	@Override
	public boolean saveDogPic(String picName) {
		User user = (User) session.getAttribute("user");
		userMapper.saveDogPic(picName,user.getId());
		return false;
	}

	@Override
	public List<String> getDogPic() {
		User user = (User) session.getAttribute("user");
		List<String> fileNames = userMapper.getDogPic(user.getId());
		
		return fileNames;
	}
}
